package work.timejay.user.controller.users;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import work.timejay.common.ApiResult;
import work.timejay.dto.UserEditDTO;
import work.timejay.dto.UserRegisterDTO;
import work.timejay.entity.User;
import work.timejay.service.CommonUserService;
import work.timejay.user.service.users.UserService;
import work.timejay.utils.LoginHelper;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wwj
 * @since 2021-12-18
 */
@RestController
@Tag(name = "用户控制层", description = "UserService")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 处理所有OAuth相关请求
     *
     * @return
     */
    @RequestMapping("/oauth2/*")
    @Operation(summary = "登录接口")
    @SaIgnore
    public Object request() {
        System.out.println("------- 进入请求: " + SaHolder.getRequest().getUrl());
        Object data = SaOAuth2Handle.serverRequest();
        JSONObject responseData = JSONUtil.parseObj(data);
        String code = responseData.getStr("code");
        if ("500".equals(code)) {
            return responseData;
        }
        JSONObject itemData = JSONUtil.parseObj(responseData.getObj("data"));
        itemData.putOpt("initStatus", LoginHelper.loginUserInfo().getInitStatus());
        responseData.putOpt("data", itemData);
        return responseData;
    }

    /**
     * 注册
     */
    @PostMapping(value = "/register")
    @SaIgnore
    public ApiResult<Object> register(@RequestBody UserRegisterDTO dto) {
        userService.saveUserInfo(dto);
        return ApiResult.success();
    }

    /**
     * 更新用户数据
     */
    @PutMapping(value = "/user")
    public ApiResult<Void> update(@RequestBody UserEditDTO dto) {
        userService.editUserInfo(dto);
        return ApiResult.success();
    }

    /**
     * 获取登录详情
     */
    @GetMapping(value = "/info")
    public ApiResult<User> getUserInfo() {
        User user = userService.getUserInfo();
        return ApiResult.success(user);
    }

    /**
     * 退出登录接口
     */
    @GetMapping(value = "/logOut")
    public ApiResult<Void> logOut() {
        StpUtil.logout(LoginHelper.loginUserInfo().getId());
        return ApiResult.success();
    }
}

